import java.io.IOException;

import model.Message;


public class SendMessage implements Runnable{
	public static final String AUTHENTICATION_TOKEN = "DQAAAK8AAACNGRDCS_R3bie665n8NGDCal3_wblZkUM7KHCyGWA-Cni2HiSiUQU9mJDrxHmMORaTPHxXS7FfgpZqdfoLizIGMBpm9f7yWIUHcdrBCSoRW_dCxg3XDpZWE9-yxodFOLmK-SPMjDTiYTRUG1ZdFEg8XaCoBCo0aKAOmuSh_B92DL7bb_lb_pclzOB2rYu1r7hV0kiZOCFZ_OAHOOtIvgVJyHIMfMDsBuaQIkC_G4TicA";
	private static final int maxNumberOfTries = 1;
	private WorkQueue workQueue;
	private Thread thread;

	public SendMessage(WorkQueue wq){
		workQueue = wq;
	}
	
	public void start(){
		if(thread == null){
			thread = new Thread(this);
			thread.start();
		}
	}
	
	public void stop(){
		thread = null;
	}
	
	@Override
	public void run() {
		System.out.println("SendMessage Started");
		while(thread == Thread.currentThread()){
			System.out.println("Try to get work");
			Message m = workQueue.getWork();
			System.out.println("Got work");
			if(m != null){
				if(m.getNumberOfTries() < maxNumberOfTries){
					try {
						boolean send = MessageUtil.sendMessage(AUTHENTICATION_TOKEN, m.getRegistrationId(), m.getMessage(), m.getGroup());
						System.out.println("Tried to send message, was it successful? " + send);
						if(!send){
							try {
								Thread.sleep(5000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							m.increaseNumberOfTries();
							workQueue.addWork(m);
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

}
